from typing import Optional, Generic, TypeVar
from dataclasses import dataclass

T = TypeVar('T')

@dataclass(frozen=True)
class LinkedList(Generic[T]):
    """不可变链表实现"""
    value: T
    next: Optional['LinkedList[T]'] = None

    def prepend(self, value: T) -> 'LinkedList[T]':
        """在头部添加元素，返回新的链表"""
        return LinkedList(value, self)

    def map(self, func: callable) -> 'LinkedList[T]':
        """映射操作，返回新的链表"""
        new_value = func(self.value)
        new_next = self.next.map(func) if self.next else None
        return LinkedList(new_value, new_next)

if __name__ == '__main__':
    # 创建一个链表：1 -> 2 -> 3 -> None
    linked_list = LinkedList(1, LinkedList(2, LinkedList(3)))

    # 在头部添加元素
    new_list = linked_list.prepend(0)

    print(id(linked_list))
    print(id(new_list))

    # 映射操作，将每个元素乘以2
    mapped_list = new_list.map(lambda x: x * 2)

    print(mapped_list)